package com.hmy.finance.service.core.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmy.finance.dal.mapper.DeviceRentalRecordMapper;
import com.hmy.finance.dal.po.DeviceRentalRecordPo;
import com.hmy.finance.job.core.dto.DailyFeeGenerateRequestDto;
import com.hmy.finance.job.core.rdto.dailyfee.WaitHandleContractRdto;
import com.hmy.finance.service.core.IDeviceRentalRecordService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;

/**
 * @author songkf
 * @description 针对表【device_rental_record(设备租赁记录表)】的数据库操作Service实现
 * @createDate 2024-02-21 18:55:01
 */
@Service
public class DeviceRentalRecordServiceImpl extends ServiceImpl<DeviceRentalRecordMapper, DeviceRentalRecordPo>
        implements IDeviceRentalRecordService {

    @Override
    public List<String> queryAllRentingDeviceContract(LocalDate startDate, LocalDate endDate, Long contractId) {
        return this.baseMapper.queryAllRentingDeviceContract(startDate.atStartOfDay(), endDate.atTime(LocalTime.MAX), contractId);
    }

    @Override
    public List<DeviceRentalRecordPo> queryRentingDeviceRentalRecordByContractId(Long contractId, LocalDate handleDate) {
        // 将 LocalDate 转换为 LocalDateTime，时间设为当天的开始时间（00:00:00）
        LocalDateTime startOfDay = handleDate.atStartOfDay();
        //查询在租的（即退租时间问Null的）或者退租时间大于handleDate的00:00:00的设备租赁记录
        LambdaQueryWrapper<DeviceRentalRecordPo> queryWrapper = Wrappers.<DeviceRentalRecordPo>lambdaQuery().eq(DeviceRentalRecordPo::getContractId, contractId)
                .and(wra -> {
                    wra.isNull(DeviceRentalRecordPo::getExpenseCycleEndTime)
                            .or()
                            .ge(DeviceRentalRecordPo::getExpenseCycleEndTime, startOfDay);
                })
                .le(DeviceRentalRecordPo::getExpenseCycleStartTime, handleDate.atTime(23, 59, 59));
        return this.baseMapper.selectList(queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateDeviceRentalRecordFeeAmount(List<DeviceRentalRecordPo> deviceRentalRecordPoList) {
        return this.baseMapper.updateDeviceRentalRecordFeeAmount(deviceRentalRecordPoList);
    }

    @Override
    public List<WaitHandleContractRdto> getWaitHandleContractInfoList(DailyFeeGenerateRequestDto dailyFeeGenerateRequestDto) {
        return baseMapper.selectWaitHandleContractInfoList(dailyFeeGenerateRequestDto.getStartDate().atStartOfDay(), dailyFeeGenerateRequestDto.getContractId());
    }
}




